<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {
            position: absolute;
            top: 50px;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: yellowgreen;
        }
    </style>
</head>

<body>
    <input type="button" id="start" value="开始">
    <input type="button" id="end" value="停止">
    <div id="box"></div>
    <script>
        var start = document.getElementById("start");
        var end = document.getElementById("end");
        var box = document.getElementById("box");
        var nowLeft = 0;
        var timer;
        start.onclick = function () {
            // 每次点击开始时先清除上一次的定时器,设表先关
            clearInterval(timer);
            timer = setInterval(function () {
                nowLeft += 10;
                box.style.left = nowLeft + "px";
            }, 50);
        };

        end.onclick = function () {
            clearInterval(timer);
        };
    </script>
</body>

</html>